/** * @Author: Joker * @Date: 2017/12/7 */
<template>
  <div>
    <el-dialog :close-on-click-modal="false" title="新建用户" :visible.sync="modal" width="600px" :before-close="handleClose">
      <div>
        <el-form :model="userForm" :rules="rules" ref="userForm" size="small" label-width="90px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="userForm.name"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model.trim="userForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input v-model.trim="userForm.pass" placeholder="请输入6-16位数字或字母"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-input v-model.trim="userForm.job">
            </el-input>
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否高管" prop="isManager">
                <el-switch
                  v-model="userForm.isManager"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="办公电话" prop="tel">
            <el-input v-model="userForm.tel"></el-input>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="userForm.phone"></el-input>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="电子邮件" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-select v-model="userForm.roles" multiple style="width: 100%">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="unit">
            <el-cascader :options="realTreeData" :props="propFather" change-on-select v-model="userForm.unit" :show-all-levels="false" style="width: 100%">
            </el-cascader>
          </el-form-item>
        </el-form>
        <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="90px" class="demo-dynamic">
          <el-row :gutter="8">
            <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'虚拟部门' + (index+1)" :key="domain.key" :prop="'domains.' + index + '.value'"
              :rules="{
                   message: '请选择虚拟部门', trigger: 'blur'
            }">
              <el-col :span="20">
                <el-cascader :options="treeData" :props="propFather" change-on-select v-model="domain.value" :show-all-levels="false" style="width: 100%">
                </el-cascader>
              </el-col>
              <el-col :span="4">
                <el-button @click.prevent="removeDomain(domain)">删除</el-button>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-button @click="addDomain">新增虚拟部门</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button-group>
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </el-button-group>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formCheck, trim } from "../../../lib/utils";
import { userManagement } from "../../../service/service_zbw";
export default {
  props: {
    addModal: {
      type: Boolean
    },
    treeData: {
      type: Array
    },
    realTreeData: {
      type: Array
    },
    roleList: {
      type: Array
    }
  },
  data() {
    //办公电话校验
    const checkTel = (rule, value, callback) => {
      //let reg = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
      let reg = /^0\d{2,3}-?\d{7,8}$/;
      let str = trim(value);
      if(!str){
        callback();
      }
      if (!reg.test(str)) {
        return callback(new Error("座机号码格式不正确"));
      }
      callback();

    };
    //手机校验
    const checkPhone = (rule, value, callback) => {
      let reg = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
      let str = trim(value);
      if (!str) {
        return callback(new Error("手机号码不能为空"));
      } else {
        if (!reg.test(str)) {
          return callback(new Error("手机号码格式不正确"));
        }
        callback();
      }
    };
    //邮箱校验
    const checkEmail = (rule, value, callback) => {
      let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      let str = trim(value);
      if(!str){
        callback();
      }
      if (!reg.test(str)) {
        return callback(new Error("邮箱地址格式不正确"));
      }
      callback();

    };
    //密码校验
    const checkPass = (rule, value, callback) => {
      let reg = /^[0-9a-zA-Z]{6,16}$/;
      let str = trim(value);
      if(!str){
        callback();
      }
      if (!reg.test(str)) {
        return callback(new Error("密码格式不正确"));
      }
      callback();
    };
    return {
      modal: this.addModal,
      userForm: {
        name: "",
        userName: "",
        isManager: false,
        pass: "",
        unit: [],
        roles: [],
        fakeUnit: [],
        job: "",
        tel: "",
        phone: "",
        email: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入用户真实姓名",
            trigger: "blur"
          },
          {
            min: 1,
            max: 10,
            message: "长度不超过10个字符",
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "blur"
          },
          {
            min: 1,
            max: 20,
            message: "长度不超过20个字符",
            trigger: "blur"
          }
        ],
        pass: [
          {
            min: 1,
            max: 15,
            validator: checkPass,
            trigger: 'blur'
          }
        ],
        unit: [
          {
            type: "array",
            required: true,
            message: "请选择部门",
            trigger: "change"
          }
        ],
        roles: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个角色",
            trigger: "change"
          }
        ],
        job: [
          {
            required: true,
            message: "请输入用户职位",
            trigger: "blur"
          },
          {
            min: 1,
            max: 10,
            message: "长度不超过10个字符",
            trigger: "blur"
          }
        ],
        tel: [
          {
            required: false,
            validator: checkTel,
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        email: [
          {
            required: false,
            validator: checkEmail,
            trigger: "blur"
          }
        ]
      },
      dynamicValidateForm: {
        domains: [
          {
            value: []
          }
        ]
      },
      //默认联动选择
      propFather: {
        value: "deptId",
        label: "deptName"
      }
    };
  },
  methods: {
    /**
       * 整理禁用数据
       */
    formatDisabled(status) {},
    /**
       * 清空表单
       */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
       * 删除一条虚拟部门
       */
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    /**
       * 新增一条虚拟部门
       */
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: [],
        key: Date.now()
      });
    },
    /**
       * 提交信息
       */
    async submit() {
      let flag = formCheck(this, "userForm");
      if (flag) {
        //判断实体部门的类型
        let type = this.checkData(
          this.userForm.unit[this.userForm.unit.length - 1],
          this.treeData
        );
        if (type) {
          if (type === 2) {
            this.$message({
              type: "error",
              message: "人员的部门不能为虚拟部门，请重新选择"
            });
            return;
          }
        }
        //虚拟部门里错误类型的序号
        if (
          this.dynamicValidateForm.domains.length > 0 &&
          this.dynamicValidateForm.domains[0].value.length > 0
        ) {
          let falseArr = [];
          for (let i = 0; i < this.dynamicValidateForm.domains.length; i++) {
            let value = this.dynamicValidateForm.domains[i].value[
              this.dynamicValidateForm.domains[i].value.length - 1
            ];
            type = this.checkData(value, this.treeData);
            if (type) {
              if (type === 1) {
                falseArr.push(i);
              }
            }
          }
          if (falseArr.length > 0) {
            this.$message({
              type: "error",
              message: `虚拟部门${falseArr + ""}为实体部门，请重新选择`
            });
            return;
          }
        }
        //判断环境是否支持 crypto 模块
        //   let crypto;
        //   try {
        //     crypto = require('crypto');
        //   } catch (err) {
        //     console.log('不支持 crypto!');
        //   }
        //   //md5加密
        //   let hashPass = crypto.createHmac('md5', this.userForm.pass)
        //     .digest('hex');
        let param = {
          deptIds: [],
          email: this.userForm.email,
          mobile: this.userForm.phone,
          name: this.userForm.name,
          passwd: this.userForm.pass,
          position: this.userForm.job,
          roleIds: this.userForm.roles,
          tel: this.userForm.tel,
          userName: this.userForm.userName,
          isManager: this.userForm.isManager
        };
        for (let i of this.dynamicValidateForm.domains) {
          if (i.value.length > 0) {
            param.deptIds.push(i.value[i.value.length - 1]);
          }
        }
        param.deptIds.push(this.userForm.unit[this.userForm.unit.length - 1]);
        let res = await userManagement.add(param);
        if (res.success) {
          this.$emit("addFinish");
          this.handleClose();
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      }
    },
    checkData(val, data) {
      let result = null;
      for (let i of data) {
        if (i.deptId === val) {
          result = i.deptType;
          return result;
        } else if (i.children && i.children instanceof Array) {
          result = this.checkData(val, i.children);
        }
      }
      return result;
    },
    /**
       * 关闭模态框
       */
    handleClose() {
      this.modal = false;
      this.$emit("closeModal", this.modal);
      this.handleReset("userForm");
    },
    /**
       * 清空表单
       */
    handleReset(name) {
      this.$refs[name].resetFields();
    }
  },
  watch: {
    addModal(newval) {
      if (newval) {
        this.modal = newval;
      }
    }
  }
};
</script>
<style scoped>

</style>

